import { useState } from 'react'
import { View, Text } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { openWebview } from '@/utils/webview'
import { openLoginPage, clearToken } from '@/utils/auth'

import './index.scss'

interface MenuItem {
  title: string
  desc?: string
  path?: string
  action?: 'logout' | 'login'
}

const MinePage = () => {
  const [token, setToken] = useState(() => Taro.getStorageSync('token'))

  useDidShow(() => {
    setToken(Taro.getStorageSync('token'))
  })

  const menuItems: MenuItem[] = [
    {
      title: '进入管理后台',
      desc: '打开全部项目与空间能力',
      path: '/#/workspaces'
    },
    {
      title: '我的收藏',
      desc: '查看收藏的模块与模板',
      path: '/#/my-favorites'
    },
    {
      title: '文档中心',
      desc: '查阅使用指南与 API',
      path: '/#/docs'
    },
    {
      title: token ? '退出登录' : '手机号登录',
      desc: token ? '清空本地 token' : '验证码快捷登录',
      action: token ? 'logout' : 'login'
    }
  ]

  const handleMenuClick = (item: MenuItem) => {
    if (item.action === 'logout') {
      clearToken()
      Taro.showToast({ title: '已退出登录', icon: 'none' })
      setToken('')
      return
    }

    if (item.action === 'login') {
      openLoginPage()
      return
    }

    if (item.path) {
      openWebview(item.path)
    }
  }

  return (
    <View className='mine-page'>
      <View className='mine-page__profile'>
        <View className='mine-page__avatar'>
          <Text>百</Text>
        </View>
        <View className='mine-page__info'>
          <Text className='mine-page__name'>百积木小程序</Text>
          <Text className='mine-page__desc'>
            {token ? '已登录，点击下方可退出' : '未登录，点击下方按钮完成登录'}
          </Text>
        </View>
      </View>

      <View className='mine-page__card'>
        {menuItems.map((item) => (
          <View
            key={item.title}
            className='mine-page__menu-item'
            onClick={() => handleMenuClick(item)}
          >
            <View>
              <Text className='mine-page__menu-title'>{item.title}</Text>
              {item.desc && (
                <Text className='mine-page__menu-desc'>{item.desc}</Text>
              )}
            </View>
            <Text className='mine-page__menu-arrow'>›</Text>
          </View>
        ))}
      </View>
    </View>
  )
}

export default MinePage
